// pages/navigator/filter/index.js
import tabbar from '../../tabbar';
const app = getApp()

Page({

  /**
   * Page initial data
   */
  data: {
    page: 1,
    pageSize: 10,
    loading: false,
    hasMore: true,
    listData:[],
    listFlag:false,
    query:'',
    banner:{},
    currentIndex: '1', // 默认选中第一个
    orders:[], // 原始订单数据
    ordersFind:[], // 筛选后的订单数据
    phone:wx.getStorageSync('phone'),
    list:tabbar,
    percent:'90',
    // 月份筛选相关
    selectedMonth: new Date().getMonth() + 1, // 默认当前月份
    monthOptions: [], // 月份选项数组
    // 分页相关
    totalCount: 0, // 总数据量
    currentPage: 1, // 当前页码
    tag:{
      content: '进行中',
      size: 'medium',
      bgColor: '#ccc',
      fontColor: '',
      plain: false,
      select: false,
      shape: 'square',
      iconName: '',
      iconSize: '',
      iconColor: ''
    }
  },
  queryInput(e){
    console.log(e.detail.value)
    this.setData({
      query: e.detail.value,
      currentPage: 1,
      orders: [],
      ordersFind: [],
      hasMore: true
    });
    this.getOrder(false);
  },
  // 月份筛选方法
  selectMonth(e){
    const selectedMonth = parseInt(e.currentTarget.dataset.month);
    this.setData({
      selectedMonth: selectedMonth,
      currentPage: 1,
      orders: [],
      ordersFind: [],
      hasMore: true
    });
    // 重新请求对应月份的数据
    this.getOrder(false);
    this.getBanner();
  },
  // 初始化月份选项
  initMonthOptions(){
    const currentMonth = new Date().getMonth() + 1;
    const monthOptions = [];
    // 生成最近6个月的选项
    for(let i = 0; i < 6; i++){
      let month = currentMonth - i;
      if(month <= 0){
        month = month + 12;
      }
      monthOptions.push(month);
    }
    this.setData({
      monthOptions: monthOptions,
      selectedMonth: currentMonth
    });
  },
  switchTab(e){
    this.setData({
      currentIndex:e.currentTarget.dataset.index,
      currentPage: 1,
      orders: [],
      ordersFind: [],
      hasMore: true
    });
    this.getOrder(false);
  },
  getBanner(){
    let _this=this;
    const selectedMonth = this.data.selectedMonth;
    const currentYear = new Date().getFullYear();
    
    wx.request({
      url: app.globalData.onlineUrl+'/getOrderBanner',
      method: 'POST',
      data: {
        month: selectedMonth,
        year: currentYear
      },
      header: {'content-type': 'application/json' }, // 请求头
      success: function (res) {
        let data=res.data.data;
        _this.setData({
          banner: data[0]
        })
      },
      fail: function (err) {
        console.log('获取banner数据失败:', err);
      }
    }); 
  },
  updateState(e){
    let _this=this;
    wx.showModal({
      title: '提示',
      content: '是否确认已回款？',
      success: function (sm) {
        if (sm.confirm) {
          wx.request({
            url: app.globalData.onlineUrl+'/updateOrderStateByMini',
            method: 'POST',
            data: {
              state:3,
              id:e.currentTarget.dataset.id
            },
            header: {'content-type': 'application/json' }, // 请求头
            success: function (res) {
              if (res.data.code === 1) {
                wx.showToast({
                  title: '操作成功',
                  icon: 'success'
                });
                _this.getOrder(false);
              } else {
                wx.showToast({
                  title: res.data.msg || '操作失败',
                  icon: 'none',
                  duration: 3000
                });
              }
            },
            fail: function (err) {
              console.error('更新订单状态失败:', err);
              wx.showToast({
                title: '网络错误，请重试',
                icon: 'none',
                duration: 3000
              });
            }
          }); 
        }
      }
    }) 
  },
  getOrder(isLoadMore = false){
    let _this=this;
    const selectedMonth = this.data.selectedMonth;
    const currentYear = new Date().getFullYear();
    const currentPage = isLoadMore ? this.data.currentPage + 1 : 1;
    
    // 防止重复请求
    if(this.data.loading) return;
    
    this.setData({
      loading: true
    });
    
    console.log('请求参数:', {
      month: selectedMonth,
      year: currentYear,
      page: currentPage,
      pageSize: this.data.pageSize,
      isLoadMore: isLoadMore
    });
    
    wx.request({
      url: app.globalData.onlineUrl+'/getOrderByMini',
      method: 'POST',
      data: {
        month: selectedMonth,
        year: currentYear,
        page: currentPage,
        pageSize: this.data.pageSize,
        state: this.data.currentIndex,
        query: this.data.query
      },
      header: {'content-type': 'application/json' }, // 请求头
      success: function (res) {
        let data = res.data.data;
        console.log('返回数据:', {
          dataLength: data.length,
          pageSize: _this.data.pageSize,
          currentPage: currentPage,
          isLoadMore: isLoadMore
        });
        
        let newOrders = isLoadMore ? [..._this.data.orders, ...data] : data;
        
        console.log('数据合并:', {
          isLoadMore: isLoadMore,
          oldOrdersLength: _this.data.orders.length,
          newDataLength: data.length,
          mergedLength: newOrders.length
        });
        
        _this.setData({
          orders: newOrders,
          currentPage: currentPage,
          loading: false,
          hasMore: data.length === _this.data.pageSize
        });
        
        console.log('更新后状态:', {
          ordersLength: newOrders.length,
          hasMore: data.length === _this.data.pageSize
        });
        
        // 后端已经完成筛选，直接显示数据
        _this.setData({
          ordersFind: newOrders
        });
      },
      fail: function (err) {
        console.log('获取订单数据失败:', err);
        _this.setData({
          loading: false
        });
      }
    }); 
  },
  deleteOrder(e){
    const id = e.currentTarget.dataset.id;
    console.log(1234567,id)
    let _this=this;
    wx.showModal({
      title: '提示',
      content: '确定要删除吗？',
      success: function (sm) {
        if (sm.confirm) {
          wx.request({
            url: app.globalData.onlineUrl+'/delOrder',
            method: 'POST',
            data:{id:id},
            header: {'content-type': 'application/json' }, // 请求头
            success: function (res) {
              _this.getOrder(false)
              _this.getBanner()
            },
            fail: function (err) {
            }
          }); 
        }
      }
    })
  },
  gotoOrderDetail(e){
    const id = e.currentTarget.dataset.id;
    console.log(1234567,id)
    wx.navigateTo({
      url: '/pages/navigator/filterDetail/index?id='+id
    });
  },
  add(e){
    wx.navigateTo({
      url: '/pages/navigator/filterAdd/index?id='+e.currentTarget.dataset.id
    });
  },
  /**
   * Lifecycle function--Called when page load
   */
  onLoad: function() {
    
  },

  /**
   * Lifecycle function--Called when page is initially rendered
   */
  onReady: function() {

  },

  /**
   * Lifecycle function--Called when page show
   */
  onShow: function() {
    this.initMonthOptions();
    // 重置分页状态
    this.setData({
      currentPage: 1,
      orders: [],
      ordersFind: [],
      hasMore: true
    });
    this.getOrder(false);
    this.getBanner();
  },

  /**
   * Lifecycle function--Called when page hide
   */
  onHide: function() {

  },

  /**
   * Lifecycle function--Called when page unload
   */
  onUnload: function() {

  },

  /**
   * Page event handler function--Called when user drop down
   */
  onPullDownRefresh: function() {

  },

  /**
   * Called when page reach bottom
   */
  onReachBottom: function() {
    if (!this.data.loading && this.data.hasMore) {
      this.loadMoreData();
    }

  },
  loadMoreData: function() {
    if (!this.data.loading && this.data.hasMore) {
      this.getOrder(true);
    }
  },

  /**
   * Called when user click on the top right corner to share
   */
  onShareAppMessage: function() {

  }
});
